package com.song.controller;


import com.song.polo.Administrator;
import com.song.polo.AjxaResultMessage;

import com.song.service.impl.AdministratorServiceImpl;
import com.song.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
public class AdministratorController {
    private AjxaResultMessage msg;
    @Autowired
    private AdministratorServiceImpl service;



    /**
     * 通过restful风获取前端数据，并返回
     * @param administratorName
     * @param password
     * @return
     */

    @RequestMapping(value = "administrator/{name}/{password}",method = RequestMethod.GET)
    @ResponseBody
    public AjxaResultMessage login(@PathVariable("name") String administratorName,@PathVariable("password") String password,HttpServletRequest request){
        System.out.println(administratorName + password);
        //AdministratorServiceImpl service = new AdministratorServiceImpl();
        Administrator administrator = service.login(administratorName, password);
       System.out.println(administrator);
        if (administrator != null){
            request.getSession().setAttribute("admin",administrator);
            service.updateLoginTime(administratorName,null, DateUtil.getTimestamp());
           msg = new AjxaResultMessage<Administrator>(200,null,null,administrator);
        }else {
            msg = new AjxaResultMessage<>(500,"用户名或密码不正确");
        }
        System.out.println(msg.getStatus());
        return msg;
    }


    /**
     * 管理员退出登录
     *
     * @param request
     */
    @RequestMapping("loginout")
    @ResponseBody
    public AjxaResultMessage loginOut(HttpServletRequest request){
        //清除session中的存值
        System.out.println("跳转");
        request.getSession().invalidate();
        return new AjxaResultMessage(200,"退出");
    }


    @ResponseBody
    @RequestMapping(value = "administrator",method = RequestMethod.POST)
    public AjxaResultMessage register(Administrator administrator){
        System.out.println(administrator);
        Integer register = service.register(administrator);
        if (register == 1) {
            msg = new AjxaResultMessage<Administrator>(200,"注册成功");
        } else if (register == 0) {
            msg = new AjxaResultMessage<Administrator>(510,"管理员名已被注册");
        } else if (register == -1) {
            msg = new AjxaResultMessage<Administrator>(511,"手机号码已被注册");
        } else {
            msg = new AjxaResultMessage<Administrator>(512,"注册失败");

        }
        return msg;
    }


}
